module.exports = (app) => {
    const express = require('express')
    const router = express.Router({
        mergeParams: true
    });

    // 保存资源
    router.post('/', async (req, res) => {
        const model = await req.Model.create(req.body)
        res.send(model)
    })

    // 获取资源列表
    router.get('/', async (req, res) => {
        const queryOptions = {}
        if(req.Model.modelName === 'Category'){
            queryOptions.populate = 'parent'
        }
        const items = req.Model.find().setOptions(queryOptions).limit(100)
        res.send(items)
    })

    // 根据id获取资源
    router.get('/:id', async (req, res) => {
        const item = await req.Model.findById(req.params.id)
        res.send(item)
    })

    // 更新资源
    router.put('/:id', async (req, res) => {
        const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })

    // 删除资源
    router.delete('/:id', async (req, res) => {
        await req.Model.findByIdAndDelete(req.params.id)
        res.send({
            success: true,
            msg: '删除成功'
        })
    })

    app.use('/admin/api/rest/:resource', async (req, res, next) => {
        const inflection = require('inflection')
        const modelName = req.params.resource;
        const model = await require('../../models/' + inflection.classify(modelName))
        req.Model = model
        await next()
    }, router)

}